<!--
 * @Author: kkk 997610780@qq.com
 * @Date: 2025-03-11 21:58:37
 * @LastEditors: kkk 997610780@qq.com
 * @LastEditTime: 2025-03-11 21:59:32
 * @FilePath: \knowledge-uni\src\components\k-get-user-info-popup\k-get-user-info-popup.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <wd-popup :model-value="modelValue" position="bottom" custom-class="rounded-lg" :safe-area-inset-bottom="true"
    @update:model-value="handleUpdate">
    <view class="k-popup">
      <view class="k-popup-des">
        建议使用您的微信头像和昵称，以便获得更好的体验
      </view>
      <view class="k-popup-body">
        <wd-form ref="formRef" :model="form" :rules="rules">
          <wd-cell title="头像" :required="true" prop="avatar" center title-width="100rpx">
            <button open-type="chooseAvatar" class="choose-avatar" @chooseavatar="handleChooseAvatar">
              <wd-icon name="add" size="42rpx" color="#909399"></wd-icon>
              <image :src="form.avatar" class="avatar-image" mode="aspectFill"></image>
              <!-- <text>添加图片</text> -->
            </button>
          </wd-cell>
          <wd-cell title="昵称" :required="true" prop="nickname" center title-width="100rpx" border>
            <wd-input v-model="form.nickname" :no-border="true" type="nickname" @blur="handleBlur"
              placeholder="请输入昵称" />
          </wd-cell>

          <wd-cell border>

          </wd-cell>

        </wd-form>
        <view class="k-popup-foot">
          <wd-button :round="false" :block="true" custom-class="w-full" @click="submit">
            确定
          </wd-button>
          <wd-button type="info" :round="false" plain :block="true" custom-class="w-full" @click="handleUpdate(false)">
            取消
          </wd-button>
        </view>
      </view>
    </view>
  </wd-popup>
</template>

<script setup>
import { fetchUpdateUserInfo } from "@/service/user";
import { showToast, uploadFile } from '@/utils/uni'
import { reactive, ref } from "vue";
import useUserStore from "@/store/user";
defineOptions({
  options: {
    styleIsolation: 'shared',
  }
});

defineProps({
  modelValue: {
    type: Boolean,
    required: true
  }
})
const userStore = useUserStore();
const formRef = ref()
const form = reactive({
  avatar: userStore.userInfo.avatar,
  nickname: userStore.userInfo.nickname,
})
const rules = reactive({
  avatar: [
    // 必填规则
    {
      required: true,
      message: '请选择头像',
      // blur和change事件触发检验
      trigger: ['blur', 'change'],
    },

  ],
  nickname: [
    // 正则判断为字母或数字
    {
      required: true,
      message: '请输入昵称',
      trigger: ['blur', 'change'],
    },
  ]
})
const emit = defineEmits(['update:modelValue'])

const header = computed(() => {
  return {
    token: userStore.token,
    version: import.meta.env.VITE_VERSION,
  }
});

function handleUpdate(v) {
  if (!v) {
    uni.showTabBar();
  }
  emit("update:modelValue", v);
}

function handleChooseAvatar(e) {
  form.avatar = e.detail.avatarUrl
}

function handleBlur({ value }) {
  form.nickname = value
}



async function handleUpdateInfo() {

  try {
    const { avatar, nickname } = form;

    const res = await uploadFile(avatar, {
      header: header.value,
    })

    const { url } = res.data;
    fetchUpdateUserInfo({
      field: "avatar",
      value: url,
    });
    await fetchUpdateUserInfo({
      field: "nickname",
      value: nickname,
    });
    handleUpdate(false);
    showToast('更新成功');
    userStore.getUserInfo();
  } catch (err) {
    showToast(err.msg || '用户信息更新失败');
  }

}


function submit() {
  formRef.value
    .validate()
    .then(({ valid }) => {
      if (valid) {
        handleUpdateInfo();
      }
    })
    .catch((error) => {
      console.log(error, 'error')
    })
}

</script>

<style lang="scss" scoped>
.k-popup {
  // padding: 30rpx;
  padding-bottom: 30rpx;

  &-des {
    padding: 60rpx 30rpx 0;
    font-size: 28rpx;
    color: var(#e8e8e8);
  }

  &-body {
    // padding: 0 15rpx;
    margin-top: 50rpx;

    .choose-avatar {
      position: relative;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      width: 150rpx;
      height: 150rpx;
      padding: 0;
      margin: 0;
      line-height: normal;
      background-color: transparent;
      border-bottom: 1px solid var(--wot-color-border-light, #e8e8e8);

      .avatar-image {
        position: absolute;
        width: 100%;
        height: 100%;
      }

      .inputAvatar {
        position: absolute;
        z-index: 2;
        width: 100%;
        height: 100%;
        opacity: 0;
      }
    }
  }

  &-foot {
    display: flex;
    flex-direction: column;
    gap: 20rpx 0;
    padding: 0 30rpx;
    margin-top: 50rpx;
  }
}
</style>
